package com.example.volleytest.adapter;

import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.example.volleytest.R;
import com.example.volleytest.datamodel.Friend;
import com.example.volleytest.network.FriendsListRequest;
import com.example.volleytest.network.VolleyHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

public class FriendsAdapter extends BaseAdapter {
    private static final int PAGE_SIZE = 10;
    private static final String FRIENDS_LIST_REQUEST_TAG = "friends_list_tag";
    private static final String URL = "http://api.vk.com/method/friends.get?user_id=1&order=name&count=" + PAGE_SIZE + "&fields=domain,photo_medium,nickname,online&name_case=nom&offset=";

    private List<Friend> friends;
    private LayoutInflater layoutInflater;
    private boolean loading;

    public FriendsAdapter(LayoutInflater layoutInflater) {
        super();
        friends = new ArrayList<Friend>();
        this.layoutInflater = layoutInflater;
        loading = false;

        loadNextPage();
    }

    @Override
    public int getCount() {
        return friends.size();
    }

    @Override
    public Object getItem(int i) {

        return friends.get(i);
    }

    @Override
    public long getItemId(int i) {
        return friends.get(i).getUserId();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (isCloseToEnd(i) && !loading) {
            loadNextPage();
        }

        if (view == null) {
            view = layoutInflater.inflate(R.layout.friend_list_item, null);

            ViewHolder holder = new ViewHolder();
            holder.avatar = (NetworkImageView)view.findViewById(R.id.avatar_iv);
            holder.avatar.setDefaultImageResId(R.drawable.default_avatar);
            holder.name = (TextView)view.findViewById(R.id.name_tv);
            holder.nickname = (TextView)view.findViewById(R.id.nickname_tv);

            view.setTag(holder);
        }

        Friend friend = friends.get(i);
        ViewHolder holder = (ViewHolder)view.getTag();
        view.setBackgroundColor(friend.isOnline() ? Color.BLUE  : Color.BLACK);
        holder.name.setText(friend.getFirstName() + " " + friend.getLastName());
        holder.nickname.setText(friend.getNickname());
        holder.avatar.setImageUrl(friend.getPhotoMedium(), VolleyHelper.getInstance().getImageLoader());

        return view;
    }

    private void loadNextPage() {
        loading = true;
        FriendsListRequest friendsListRequest = new FriendsListRequest(Request.Method.GET, URL + Integer.toString(friends.size()), new Response.Listener<Collection<Friend>>() {
            @Override
            public void onResponse(Collection<Friend> response) {
                if (response != null) {
                    appendItemsToList(response);
                    notifyDataSetChanged();
                } else {
                    Log.d("KVEST_TAG", "response is null");
                }
                loading = false;
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading = false;
                Log.d("KVEST_TAG", "onErrorResponse=" + error.getMessage());
            }
        });
        friendsListRequest.setTag(FRIENDS_LIST_REQUEST_TAG);
        VolleyHelper.getInstance().addRequest(friendsListRequest);
    }

    public void appendItemsToList(Collection<Friend> response) {
        friends.addAll(response);
    }

    public void cancelRequests() {
        VolleyHelper.getInstance().cancelAll(FRIENDS_LIST_REQUEST_TAG);
    }

    private static class ViewHolder {
        public NetworkImageView avatar;
        public TextView name;
        public TextView nickname;
    }

    private boolean isCloseToEnd(int shownIndex) {
        return (friends.size() - shownIndex < 2);
    }
}
